package com.lw.extraceim.ui.activity.es;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.Polyline;
import com.baidu.mapapi.map.PolylineOptions;
import com.baidu.mapapi.model.LatLng;
import com.google.gson.reflect.TypeToken;
import com.lljjcoder.style.citylist.Toast.ToastUtils;
import com.lw.extraceim.R;
import com.lw.extraceim.app.AppConstants;
import com.lw.extraceim.loader.RouteLoader;
import com.lw.extraceim.model.ExpressSheet;
import com.lw.extraceim.model.PackageRoute;
import com.lw.extraceim.net.HttpResponseParam;
import com.lw.extraceim.net.ResponseCode;
import com.lw.extraceim.net.callback.HttpResponseParamCallback;
import com.lw.extraceim.ui.activity.base.BaseActivity;
import com.lw.extraceim.util.JsonUtils;
import com.lw.extraceim.util.MapUtils;
import com.lw.extraceim.view.ExtraceToolbar;

import org.json.JSONException;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.Call;

/**
 * @Author : liwei
 * @Email : 1759840027@qq.com
 * @Description : 快件信息的详细界面，包括快件的位置信息 需要用到百度地图的位置追踪，路线绘制等技术
 * @Date : 2019/4/21 10:02
 */
public class ExpressSheetInfoActivity extends BaseActivity {

    private static final String TAG = "ExpressSheetInfoActivit";

    private ExtraceToolbar mToolbar;

    private ImageView mIvExpressSheetImg;
    private TextView mTvExpressSheetId;
    private Button mButtonCopy;
    private TextView mTvExpressSheetStatus;
    private ImageButton mIbEditEs;


    private MapView mEsPositionMap;
    BitmapDescriptor startBD = BitmapDescriptorFactory
            .fromResource(R.drawable.ic_me_history_startpoint);
    BitmapDescriptor finishBD = BitmapDescriptorFactory
            .fromResource(R.drawable.ic_me_history_finishpoint);
    private TextView mTvNoEsPositionInfo; //显示没有快件位置信息

    private ExpressSheet expressSheet;
    List<PackageRoute> routeList;
    private RouteLoader loader;

    private String action; //页面功能


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void initView() {
        setContentView(R.layout.activity_express_sheet_info);
        mToolbar = findViewById(R.id.toolbar);
        initToolBar();

        mIvExpressSheetImg = findViewById(R.id.iv_express_sheet_img);
        mTvExpressSheetId = findViewById(R.id.tv_express_sheet_id);
        mButtonCopy = findViewById(R.id.button_copy);
        mTvExpressSheetStatus = findViewById(R.id.tv_express_sheet_status);
        mEsPositionMap = findViewById(R.id.es_position_map);
        mTvNoEsPositionInfo = findViewById(R.id.tv_no_es_position_info);
        mIbEditEs = findViewById(R.id.ib_edit_es);
    }

    /**
     * 初始化toolBar
     */
    protected void initToolBar() {
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        mToolbar.setBackButtonOnClickListerner(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ExpressSheetInfoActivity.this.finish();
            }
        });
    }
    @Override
    public void initData() {
        Intent intent = getIntent();
        loader = new RouteLoader(this);
        expressSheet = (ExpressSheet) intent.getSerializableExtra("es");
        action = intent.getStringExtra("action");

        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                Log.d(TAG, "run: " + System.currentTimeMillis());
                if (expressSheet != null) {
                    loadRoute(expressSheet.getId());
                }
            }
        }, 0, 60000);
        Log.d(TAG, "initData: " + expressSheet);
    }

    @Override
    public void refreshUI() {
        if( expressSheet != null) {
            mEsPositionMap.setVisibility(FrameLayout.VISIBLE);
            mTvNoEsPositionInfo.setVisibility(FrameLayout.GONE);
            mTvExpressSheetId.setText(expressSheet.getId());
            mTvExpressSheetStatus.setText(expressSheet.getStatusString());
        }else{
            mEsPositionMap.setVisibility(FrameLayout.GONE);
            mTvNoEsPositionInfo.setVisibility(FrameLayout.VISIBLE);
        }
    }

    @Override
    public void initEvent() {
        mButtonCopy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //获取剪贴板管理器：
                ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                // 创建普通字符型ClipData
                ClipData mClipData = ClipData.newPlainText("es_id", mTvExpressSheetId.getText());
                // 将ClipData内容放到系统剪贴板里。
                cm.setPrimaryClip(mClipData);
                ToastUtils.showShortToast(ExpressSheetInfoActivity.this,"已复制");
            }
        });
        mIbEditEs.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                WriteExpressSheetActivity.actionStart(ExpressSheetInfoActivity.this, AppConstants.ACTION_EDIT, expressSheet);
            }
        });

    }
    //更新map地图
    public void refreshMapMapView() {
        if (routeList != null && !routeList.isEmpty() && routeList.size() > 2) {
            Marker mMarkerA;
            Marker mMarkerB;
            InfoWindow mInfoWindow;
            //更新mapView中的信息
            BaiduMap mBaiduMap = mEsPositionMap.getMap();
            // 开启定位图层
            mBaiduMap.setMyLocationEnabled(true);
            Polyline mPolyline;
            Log.d(TAG, "refreshMapMapView: " + routeList);
            mBaiduMap.clear();//清空map的所有信息
            List<LatLng> latLngs = MapUtils.coordinateConvert(routeList);//将routeList的点转换为百度坐标点
            MapStatus.Builder builder = new MapStatus.Builder();
            builder.target(latLngs.get(0)).zoom(18f);
            mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
            MarkerOptions oStart = new MarkerOptions();//地图标记覆盖物参数配置类
            oStart.position(latLngs.get(0));//覆盖物位置点，起点
            Log.d(TAG, "refreshMapMapView: " + latLngs.get(0));
            Log.d(TAG, "refreshMapMapView: " + latLngs.get(latLngs.size() - 1));
            oStart.icon(startBD);//设置覆盖物图片
            // oStart.zIndex(1);//设置覆盖物Index
            mMarkerA = (Marker) (mBaiduMap.addOverlay(oStart)); //在地图上添加此图层
            //添加终点图层
            MarkerOptions oFinish = new MarkerOptions().position(latLngs.get(latLngs.size() - 1)).icon(finishBD);
            mMarkerB = (Marker) (mBaiduMap.addOverlay(oFinish));
            OverlayOptions ooPolyline = new PolylineOptions().width(13).color(0xAAFF0000).points(latLngs);
            mPolyline = (Polyline) mBaiduMap.addOverlay(ooPolyline);
        }
    }

    public void loadRoute(String esId) {
        loader.getExpressSheetRoute(esId, new HttpResponseParamCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                alert("网络错误" + e.getMessage());
            }

            @Override
            public void onResponse(HttpResponseParam response, int id) {
                Log.d(TAG, "onResponse: " + response.reseponseJson);
                if (response.code.getCode() == ResponseCode.SUCESS) {
                    try {
                        routeList = JsonUtils.fromJson(response.reseponseJson.getJSONArray("routeList").toString(), new TypeToken<List<PackageRoute>>() {
                        });
                        refreshMapMapView();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    alert("获取位置信息失败");
                }
            }
        });
    }



    @Override
    public void onBackPressed() {
        this.finish();
    }

    /**
     * 启动ExpressSheetInfoActivity
     * @param context
     * @param es
     */
    public static void actionStart(Context context, ExpressSheet es){
        Intent intent = new Intent(context,ExpressSheetInfoActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("es",es);
        intent.putExtras(bundle);
        context.startActivity(intent);
    }
}
